package bank;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

public class _23MergeKLists {
    public static ListNode22 mergeKLists(ListNode22[] lists) {
        int len = lists.length;
        if(len == 0){
            return null;
        }
        List<ListNode22> listss = new ArrayList<>(len);
        for (int i = 0;i < len;i++){
            if(lists[i] != null){
                listss.add(lists[i]);
            }
        }
        len = listss.size();
        if(len == 0){
            return null;
        }

        ListNode22 res = new ListNode22();
        ListNode22 p = res;
        //我真的累了呀，就用暴力解法吧
        List<Integer> listInt = new ArrayList<>();
        for(int i = 0;i < len;i++){
            ListNode22 ps = listss.get(i);
            for(int j = 0;j < getLen(listss.get(i));j++){
                listInt.add(ps.val);
                ps = ps.next;
            }
        }
        //取到所有数据的集合listInt后，排序后再赋值给res
        Collections.sort(listInt);
        for(int i = 0;i < listInt.size();i++){
            p.next = new ListNode22(listInt.get(i));
            p = p.next;
        }
        p = null;
        return res.next;
    }

    private static int getLen(ListNode22 listNode22) {
        int num = 0;
        ListNode22 p = listNode22;
        while (p != null){
            p = p.next;
            num++;
        }
        return num;
    }

    public static class ListNode22 {
        int val;
        ListNode22 next;

        ListNode22() {
        }

        ListNode22(int val) {
            this.val = val;
        }

        ListNode22(int val, ListNode22 next) {
            this.val = val;
            this.next = next;
        }
    }
}
